<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use app\BaseController;
use think\facade\{Db, Log};
use think\exception\ValidateException;

use app\common\model\{Cate, User, Banner, Product, ProductCate, ProductSku, Img, Order, Sku, UserAddress, AboutUs};
use app\common\validate\{UserValidate, ProductValidate, ProductCateValidate, OrderValidate};

class HomeController extends BaseController
{
    /** 
     * 上传图片 
     */
    public function img_up()
    {
        $data = input('');
    
        try{
            validate(ImgValidate::class)->scene('img')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
    
        $files = request()->file();
    
        if(!$files){
            $this->error_back('上传文件为空');
        }
    
        $imgs = [];
        foreach($files as $file){
            if(explode('/', $file->getMime())[0] !== 'image'){
                continue;
            }
            
            $imgs[] = fileUp($file, $data['path']);
        }
    
        $this->success_back('上传成功', $imgs);
    }

    /**
	 * 轮播图列表
	 */
    public function getBannerList()
    {
        if(request()->isPost()){
            $bannerModel = new Banner();
            $field = 'id, img';
            $list = $bannerModel->getList([], 0, 0, 0, $field, 'id DESC');

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 产品分类列表
	 */
    public function getProductCateList()
    {
        if(request()->isPost()){
            $cateModel = new ProductCate();

            $list = $cateModel->getList([], 0);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 产品列表
	 */
    public function getProductList()
    {
        if(request()->isPost()){
            $data = input('');

            try{
                validate(ProductValidate::class)->scene('list_api')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $productModel = new Product();

            $where[] = ['cate_id', '=', $data['cate_id']];
            
            $field = 'id, name, show_img, price';
            $list = $productModel->getList($where, 1, $data['page'], $data['limit'], $field, 'sales DESC, id DESC');

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 产品详情
	 */
    public function getProductShow()
    {
        if(request()->isPost()){
            $data = input('post.');

            try{
                validate(ProductValidate::class)->scene('show')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $productModel = new Product();

            $field = 'id, name, price, sales, content';
            $info = $productModel->getFind(['id' => $data['product_id']], $field);

            if($info['code'] != 'ok'){
                $this->error_back($info['msg']);
            }

            $imgModel = new Img();
            $productSkuModel = new ProductSku();

            $whereImg = [
                'obj_type' => 1,
                'obj_cate' => 1,
                'obj_id'   => $data['product_id'],
            ];

            /** 查询产品的轮播图 */
            $imgList = $imgModel->getList($whereImg, 0)['data'];
            $imgList = $imgList->toArray();

            /** 查询产品的规格 */
            $skuList = $productSkuModel->getSkuList($data['product_id']);

            $info['data']['banner_list'] = array_column($imgList, 'img');
            $info['data']['sku_list']    = $skuList;

            $this->success_back('ok', $info['data']);
        }
    }

    /**
	 * 提交订单
	 */
    public function addOrder()
    {
        if(request()->isPost()){
            $data = input('post.');

            try{
                validate(OrderValidate::class)->scene('add')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $skuModel     = new Sku();
            $orderModel   = new Order();
            $productModel = new Product();
            $addressModel = new UserAddress();

            $skuInfo = $skuModel->getFind(['id' => $data['sku_id']]);

            if($skuInfo['code'] != 'ok'){
                $this->error_back('规格属性不存在');
            }

            $addressInfo = $addressModel->getFind(['id' => $data['address_id']]);

            if($addressInfo['code'] != 'ok'){
                $this->error_back('地址不存在');
            }

            $productInfo = $productModel->getFind(['id' => $data['product_id']]);

            if($productInfo['code'] != 'ok'){
                $this->error_back('产品不存在');
            }

            $addData = [
                'order_no'     => getOrderNo(),
                'user_id'      => $data['user_id'],
                'product_id'   => $data['product_id'],
                'total'        => $data['total'],
                'sku_name'     => $skuInfo['data']['name'],
                'take_name'    => $addressInfo['data']['name'],
                'take_mobile'  => $addressInfo['data']['mobile'],
                'take_address' => $addressInfo['data']['address'],
            ];

            $flag = $orderModel->add($addData);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            $this->success_back('提交订单成功', (int)$flag['data']);
        }
    }

    /**
     * 订单支付
     */
    public function payOrder()
    {
        $data = input('');

        try{
            validate(OrderValidate::class)->scene('pay')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel    = new User();
        $orderModel   = new Order();
        $productModel = new Product();

        $orderInfo = $orderModel->where(['id' => $data['order_id']])->find();
        $userInfo  = $userModel->where(['id' => $data['user_id']])->find();
        $productInfo  = $productModel->where(['id' => $orderInfo->getData('product_id')])->find();

        $payData['openid']    = $userInfo['openid'];
        $payData['order_no']  = $orderInfo['order_no'];
        $payData['total_fee'] = $orderInfo['price'];
        $payData['body']      = $productInfo['name'];
        $payData['notify']    = 'notify';

        $payController = new WxpayController();
        $res = $payController->pay($payData);

        if($res['code'] == 200){
            $this->success_back('操作成功', $res['sign']);
        }else{
            $this->error_back($res['return_msg']);
        } 
    }

    /**
     * 介绍
     */
    public function getAboutInfo()
    {
        $info = (new AboutUs())->getFind(['id' => 1]);

        if($info['code'] != 'ok'){
            $this->error_back($info['msg']);
        }

        $this->success_back('ok', $info['data']);
    }
}